package com.qidian.buy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qidian.buy.mapper.ItemCategoryMapper;
import com.qidian.buy.pojo.ItemCategory;
import com.qidian.buy.service.ItemCategoryService;
import com.qidian.buy.util.QdConstant;
import com.qidian.buy.util.pojo.QdResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 * @date 2023/9/8 9:42
 */
@Service
public class ItemCategoryServiceImpl implements ItemCategoryService {
    @Autowired
    private ItemCategoryMapper categoryMapper;
    @Override
    public QdResult queryByParentId(Long parentId) {
        QueryWrapper<ItemCategory> wrapper = new QueryWrapper<>();
        wrapper.ne("status", QdConstant.DATA_DELETED);// 排除删除的数据
        wrapper.eq("parent_id",parentId);
        return QdResult.ok(categoryMapper.selectList(wrapper));
    }

    @Override
    public QdResult save(ItemCategory category) {
        // 去重
        QueryWrapper<ItemCategory> wrapper = new QueryWrapper<>();
        wrapper.ne("status", QdConstant.DATA_DELETED);// 排除删除的数据
        wrapper.eq("parent_id",category.getParentId());
        wrapper.eq("cat_name",category.getCatName());
        if(categoryMapper.selectOne(wrapper) != null){
            return QdResult.duplicate("类型的名字重复");
        }
        category.setCreateTime(new Date());
        category.setModifyTime(new Date());
        category.setStatus(1);
        int insert = categoryMapper.insert(category);
        if(insert == 1 && category.getParentId() != 0){
            // 添加成功,判断当前类目的父类目的parent表示是否是1，如果不是就修改为1，如果是就算了。
            ItemCategory catParent = categoryMapper.selectById(category.getParentId());
            if(catParent.getParent() == 0){
                catParent.setParent(1);
                catParent.setModifyTime(new Date());
                categoryMapper.updateById(catParent);
            }
        }
        return QdResult.isOk(insert);
    }
}
